//@version=5
strategy('Trust Signals', overlay=1)

src = close
 
Ema200       = input.bool(true, "EMA 200")
plot(Ema200 ? ta.ema(close, 200) : na, title="EMA 200", editable=true )

keyvalue = input.float(3, title='Reactivity', step=.1)
atrperiod = input(10, title='Depth')
isADX = input(false, title='ADX Filtering')

adxlen = input(21, title='ADX Smoothing')
dilen = input(21, title='DI Length')
dirmov(len) =>
    up = ta.change(high)
    down = -ta.change(low)
    plusDM = na(up) ? na : up > down and up > 0 ? up : 0
    minusDM = na(down) ? na : down > up and down > 0 ? down : 0
    truerange = ta.rma(ta.tr, len)
    plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
    minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
    [plus, minus]
adx(dilen, adxlen) =>
    [plus, minus] = dirmov(dilen)
    sum = plus + minus
    adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
    adx
sig = adx(dilen, adxlen)

xATR = ta.atr(atrperiod)
nLoss = keyvalue * xATR

xATRTrailingStop = 0.0
iff_1 = src > nz(xATRTrailingStop[1], 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : iff_2

pos = 0
iff_3 = src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0)
pos := src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0) ? 1 : iff_3

xcolor = pos == -1 ? color.red : pos == 1 ? color.green : color.blue


buy = ta.crossover(src, xATRTrailingStop)
sell = ta.crossunder(src, xATRTrailingStop)
barcolor = src > xATRTrailingStop

plotshape(not isADX and buy, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.blue, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(not isADX and sell, title='Sell', text='Sell', style=shape.labeldown, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)


plotshape(isADX and sig > 30 and buy, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.blue, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(isADX and sig > 30 and sell, title='Sell', text='Sell', style=shape.labeldown, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)

barcolor(barcolor ? color.blue : color.red)

//Alerts 

alertcondition(buy, "BUY", "Alert")
alertcondition(sell, "SELL", "Alert")
alertcondition(buy or sell, " Alert-Trusted Signals ", "Alert")


//strategy


strategy.entry(id='Long', direction=strategy.long, when= buy )
strategy.close(id='Long', when= sell)

strategy.entry(id='Short', direction=strategy.short, when= sell)
strategy.close(id='Short', when= buy )

